<template>
  <div class="main-container">
    <Condition>
      <!-- 任务名称 -->
      <div class="condition-item">
        <span class="condition-label">任务名称</span>
        <el-input 
          class="condition-input" 
          v-model="pageData.name" 
          placeholder="请输入任务名称"
          @change="filterName" 
          clearable
        ></el-input>
      </div>
      <!-- 任务状态 -->
      <div class="condition-item">
        <span class="condition-label">任务状态</span>
        <el-select @change="filterStatus" class="condition-input" v-model="pageData.status" clearable placeholder="请选择任务状态">
          <el-option 
            v-for="(item, index) in taskStatus" 
            :key="index" 
            :label="item.label" 
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
    </Condition>
    <!-- 数据表格部分 -->
    <div class="data-show">
      <div class="data-title data-actions data-title-between">
        <span class="action aniTxtBtn" @click="linkToCreate">新建任务</span>
        <!-- 切换任务列表 -->
        <div class="data-title-actions">
          <el-radio 
            class="transition-radio"
            v-for="(item, index) in fusionTypes" 
            v-model="fusionType"
            :key="index"
            :value="item.value"
            :label="item.label"
            @change="fusionTypeChange"
          ></el-radio>
        </div>
      </div>
      <!-- 底下表格 -->
      <div class="data-table">
        <el-table border v-loading="pageData.loading" :data="pageData.data" stripe show-header>
          <el-table-column label="序号" align="center" type="index" width="100" />
          <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="目标用户" show-overflow-tooltip align="center" prop="infoData.targetUserId" />
          <el-table-column label="参数" align="center" prop="infoData.parameter" />
          <el-table-column label="媒体类型" align="center" show-overflow-tooltip prop="infoData.module">
            <template #default="{ row }">
              {{ getShow(row.infoData.module, 'value', modules, 'label') }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template #default="{ row }">
              {{ getShow(row.status, 'value', taskStatus, 'label') }}
            </template>
          </el-table-column>
          <el-table-column label="任务描述" align="center" show-overflow-tooltip prop="description" />
          <el-table-column label="创建时间" align="center" show-overflow-tooltip prop="createTime" />
          <el-table-column label="操作" align="center" width="280" fit>
            <template #default="scope">
              <div class="table-actions">
                <button class="aniTxtBtn blue" @click="linkToDetail(scope.row)">任务进度</button>
                <button class="aniTxtBtn red" @click="delItem(scope.row)">删除</button>
              </div>
            </template>
          </el-table-column>
          <!-- 没有数据时显示 -->
          <template #empty>
            <i class="iconfont icon-wushuju1 data-empty-icon"></i>
            <h3 class="data-empty">暂无数据</h3>
          </template>
        </el-table>
      </div>
      <Pagination 
        :total="pageData.total"
        v-model:page="pageData.page"
        v-model:limit="pageData.pageSize"
        @pagination="pageChange"
      />
    </div>
  </div>
</template>
<script setup>
import Condition from '@/components/common/Condition.vue';
import Pagination from '@/components/common/Pagination.vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { ref, computed, onActivated } from 'vue';
import { API } from '@/utils/status.js';
import { useRouter } from 'vue-router';
import * as request from '@/api/steganography';

const router = useRouter();

// ============> 假数据 <============
const systems = API.steganography.systems;
const fusionTypes = API.fusion.fusionOneTaskType;
const modules = API.steCommon.modules;

// ============> data <============
let taskStatus = ref(API.fusion.appTwoImplantStatus);
// 切换任务类型时保存的参数对象
let savedPageData = {
  loading: false,
  name: '',
  status: null,
  // totalCount
  total: 0,
  // pageNo
  page: 1,
  pageSize: 10,
  // totalPage
  pageCount: 5,
  data: []
};
const pageData = ref({
  loading: false,
  name: '',
  status: null,
  // totalCount
  total: 0,
  // pageNo
  page: 1,
  pageSize: 10,
  // totalPage
  pageCount: 5,
  data: []
});
// 任务类型绑定变量
const fusionType = ref(0);
const getShow = computed(() => {
  return function (v, k, arr, returnKey){
    let obj = arr.find(item => item[k] === v);
    let res = obj ? obj[returnKey] : '';
    return res;
  }
});

// ============> hooks <============
getList();
onActivated(() => {
  getList();
})

// ============> method <============
function filterName(){
  pageData.value.name = e;
  pageData.value.page = 1;
  getList();
}
function filterStatus(){
  pageData.value.status = e;
  pageData.value.page = 1;
  getList();
}
// 跳转到创建任务
function linkToCreate(){
  let fusionName = fusionType.value === 0 ? 'generateSender' : 'generateReceiver';
  router.push({ 
    name: fusionName,
    query: {
      isCreate: true
    } 
  });
}
// 任务进度跳转
function linkToDetail(item){
  let routerName = fusionType.value === API.steganography.type.IMPLANT ? 'generateSender' : 'generateReceiver';
  router.push({
    name: routerName,
    query: {
      id: item.id
    }
  });
}
// 切换任务类型事件
function fusionTypeChange(e){
  taskStatus.value = e === API.steganography.type.IMPLANT ? API.fusion.appTwoImplantStatus : API.fusion.appTwoExtractStatus;
  // 中间参数对象
  const tempPageData = Object.assign({}, pageData.value);
  pageData.value = Object.assign({}, savedPageData);
  getList();
  savedPageData = Object.assign({}, tempPageData);
}
// 页面改变
function pageChange(e){
  pageData.value.page = e.page;
  pageData.value.pageSize = e.limit;
  getList();
}
// 拉取任务列表
function getList(){
  pageData.value.loading = true;
  request.getList({
    status: pageData.value.status,
    name: pageData.value.name,
    pageNo: pageData.value.page,
    pageSize: pageData.value.pageSize,
    taskType: fusionType.value,
    moduleType: API.steganography.moduleType.APPTWO
  })
  .then(res => {
    console.log(res)
    pageData.value.data = res.list;
    pageData.value.page = res.pageNo;
    pageData.value.total = res.totalCount;
    pageData.value.pageCount = res.totalPage;
    pageData.value.loading = false;
    initDatas();
  })
  .catch(err => {
    console.log(err);
    pageData.value.loading = false;
  })
}
// 过滤数据
function initDatas(){
  if (Array.isArray(pageData.value.data) && pageData.value.data.length > 0){
    pageData.value.data.forEach(item => {
      item.infoData = JSON.parse(item.infoData)
      item.delFlag = false;
    });
  }
}
// 删除
function delItem(item){
  if (item.delFlag) {
    ElMessage.warning('当前任务正在删除，请稍后再试');
    return;
  }
  ElMessageBox.confirm('您是否确认删除此任务？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(() => {
      item.delFlag = true;
      request.del({
        id: item.id
      })
        .then(res => {
          console.log(res);
          ElMessage.success('删除任务成功！');
          item.delFlag = false;
          getList();
        })
        .catch(err => {
          console.log(err);
          item.delFlag = false;
          let msg = err.msg || err.message || '删除任务失败，请稍后重试或联系管理员';
          ElMessage.error(msg);
        })
    })
    .catch(() => {})
}
</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.table-actions {
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  height: 100%;
  .action {
    width: 80px;
  }
}
.green {
  color: var(--color-green);
}
.red {
  color: var(--color-red);
  @include red-text-shadow;
}
.blue {
  color: var(--color-primary);
  @include blue-text-shadow;
}
.main-color {
  color: var(--color-main);
  @include main-text-shadow;
}
.data-title {
  height: 50px;
}
.data-title-between {
  @include flex-between-center;
  .data-title-actions {
    @include flex-all-center;
    height: 40px;
    padding: 4px 8px;
    border-radius: 8px;
    background-color: var(--color-white-10);
    // border: 1px solid var(--color-gray-10);
    .el-radio {
      @include flex-all-center;
      margin: 0 4px;
      height: 36px;
      min-width: 80px;
      border-radius: 4px;
      background-color: var(--color-radio-background);
      &::v-deep .el-radio__input {
        display: none;
      }
      &::v-deep .el-radio__label {
        padding: 0 4px;
      }
    }
    .el-radio.is-checked {
      background-color: var(--color-main);
    }
    .el-radio.is-checked::v-deep .el-radio__label {
      color: var(--color-white-10)!important;
    }
  }
}
.transition-radio {
  transition: all 0.3s linear;
}
</style>